<?php

namespace app\common\model;

use think\Cache;
use think\Db;
use think\db\Expression;
use think\Model;

class IntegralGoods extends Model
{

    // 表名
    protected $name = 'integral_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
    ];

    protected static function base($query)
    {
        $query->where(['is_shelves' => 1, 'deletetime' => null]);
    }

    public function getCoverAttr($value, $data)
    {
        return $value ? cdnurl($value, true) : $value;
    }

    /**
     * @param array $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($params = [])
    {
        $sort       = !empty($params['sort']) && in_array($params['sort'], ['integral', 'sales_count', 'distance']) ? $params['sort'] : 'id';
        $order      = !empty($params['order']) && strtoupper($params['order']) == 'ASC' ? 'ASC' : 'DESC';
        $where      = [];
        $distances  = [];

        if ($sort === 'distance') {
            if (empty($params['site'])) {
                return self::where(['id' => -1])->paginate();
            }

            if (Cache::tag('geo')->get('geo:integralgoods') !== true) {
                self::addIntegralGoodsToRedis();
            }

            list($lat, $lng) = strpos($params['site'], ',') !== false ? explode(',', $params['site']) : [DEFAULT_LATITUDE, DEFAULT_LONGITUDE];

            $redis = Cache::store('redis')->handler();
            $georadiuslist = [];
            if (method_exists($redis, 'georadius')) {
                $georadiuslist = $redis->georadius('geo:integralgoods', $lng, $lat, 15, 'km', ['WITHDIST', 'COUNT' => 200, 'ASC']);
            }

            $sort   = 'id';
            $order  = 'ASC';
            $ids    = [];
            if ($georadiuslist) {
                $ids        = array_column($georadiuslist, 0);
                $distances  = array_column($georadiuslist, 1);
                $distances  = array_combine($ids, $distances);
                $sort       = new Expression('FIELD(`id`, ' . implode(',', $ids) . ')');

            }
            $where['id'] = ['IN', $ids];
        }

        $list = self::where($where)->order($sort, $order)->paginate();

        foreach ($list as &$v) {
            $v['flag']          = __('Integral_goods');
            $v['url']           = '/pages/home/integral-goods-detail';
            $v['button_text']   = __('Redeem now');
            if (isset($distances[$v['id']])) {
                $v['distance'] = $distances[$v['id']];
            }
        }

        return $list;
    }

    /**
     * 添加积分商品到redis
     * @throws \think\exception\DbException
     */
    public static function addIntegralGoodsToRedis()
    {
        $goods = self::all();
        $redis = Cache::store('redis')->handler();

        foreach ($goods as $v) {
            if (method_exists($redis, 'geoadd')) {

                if (isset($v['region_id'])) {
                    $site       = get_center_from_degrees(Db::name('RegionLocation')->where(['region_id' => $v['region_id']])->column('lng,lat', 'id'));
                    $v['lat']   = $site['lat'];
                    $v['lng']   = $site['lng'];
                } else {
                    list($v['lat'], $v['lng']) = [DEFAULT_LATITUDE, DEFAULT_LONGITUDE];
                }

                $redis->geoadd('geo:integralgoods', $v['lng'], $v['lat'], $v['id']);
            }
        }
        Cache::tag('geo')->set('geo:integralgoods', true, 60 * 60 * 24 * 7);
    }

    /**
     * 获取首页推荐积分商品
     */
    public static function getHomoRecommend($lng = 0, $lat = 0)
    {
        $list = Cache::tag('api')->get('integral_goods_homo_recommend');
        if (!$list) {
            $list = self::where(['is_homo_recommend' => 1])->order('sales_count DESC,id DESC')->select();
            foreach ($list as &$v) {
                $v['flag']      = __('Integral_goods');
                $v['url']       = '/pages/home/integral-goods-detail';
                $v['button_text']   = __('Redeem now');
            }
            Cache::tag('api')->set('integral_goods_homo_recommend', $list, 60 * 60);
        }

        return $list;
    }

    /**
     * 获取详情
     */
    public function getDetail($id = null)
    {
        $data = self::where(['id' => $id])->order('id DESC')->find();
        if (isset($data['images'])) {
            $data['images'] = explode(',', $data['images']);
        }
        return $data;
    }
}
